package master

import (
	"encoding/json"
	"gitee.com/alone.com/go-crontab/crontab/common"
	"net"
	"net/http"
	"strconv"
	"time"
)

type ApiService struct {
	httpServer *http.Server
}

var (
	G_apiService *ApiService
)

// 初始化服务
func InitApiServer() (err error) {
	serveMux := http.NewServeMux()
	serveMux.HandleFunc("/job/save", handleJobSave)
	serveMux.HandleFunc("/job/delete", handleJobDelete)

	listener, err := net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPort))
	if err != nil {
		return err
	}

	httpServer := &http.Server{
		ReadTimeout:  time.Duration(G_config.ApiReadTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(G_config.ApiWriteTimeout) * time.Millisecond,
		Handler:      serveMux,
	}

	G_apiService = &ApiService{
		httpServer: httpServer,
	}

	go httpServer.Serve(listener)

	return
}

// 保存任务接口 POST{"name":"", "command":"", "cronExpr":"xxx"}
func handleJobSave(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
	}

	postJob := r.PostForm.Get("job")
	job := &common.Job{}
	err = json.Unmarshal([]byte(postJob), job)
	if err != nil {
	}

	oldJob, err := G_JobMgr.SaveJob(job)
	if err != nil {
		return
	}

	resp, err := common.Success(0, "success", oldJob)
	if err == nil {
		w.Write(resp)
	}
	return
}

func handleJobDelete(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
	}

	name := r.PostForm.Get("name")

	return
}
